package com.weavernorth.updateKaoQin;

import com.weaver.general.BaseBean;
import com.weaver.general.Util;
import com.weavernorth.util.Logger4jUtil;
import com.weavernorth.util.SendEmail.ExchangeClient;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.ConnectionPool;
import weaver.conn.RecordSet;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.wechat.util.Utils;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Date;

import static com.weavernorth.util.dateUtils.*;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.updateKaoQin
 * @date: 2021/9/7 17:55
 * @description: 定时任务：异常考勤发送邮件
 */
public class zKqInfoSendMailTimmer extends BaseCronJob {
    public static ConnectionPool pool = ConnectionPool.getInstance();
    public Connection conn;
    public Statement statement;
    public String cycle;
    private String gh;
    private String ny;

    public String getGh() {
        return gh;
    }

    public void setGh(String gh) {
        this.gh = gh;
    }

    public String getNy() {
        return ny;
    }

    public void setNy(String ny) {
        this.ny = ny;
    }

    @Override
    public void execute() {
        Logger log = new Logger4jUtil().getLogger("/Timmer/zKqInfoSendMailTimmer/");
        log.info("定时任务：异常考勤发送邮件======>");
        Long begin = new Date().getTime();
        BaseBean bb = new BaseBean();
        String nowDate=getYearMonthDay();//当前日期
        String senderHost = Util.null2String(bb.getPropValue("configMail", "senderHost"));//"smtp.qq.com";//邮件发送的服务器
        //String protocol = Util.null2String(bb.getPropValue("configMail", "protocol"));//邮件协议
        //String port = Util.null2String(bb.getPropValue("configMail", "port"));//端口
        String senderEmail = Util.null2String(bb.getPropValue("configMail", "senderEmail"));//发件人邮箱
        String senderPassword = Util.null2String(bb.getPropValue("configMail", "senderPassword"));//发件人邮箱密码(授权码)
        ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
                .hostname(senderHost)
                .exchangeVersion(ExchangeVersion.Exchange2010)
                .username(senderEmail)
                .password(senderPassword).build();
        String strGh = "";
        String strNY = previousMonth();//上月日期
        if (gh != null) {
            strGh = gh;
        }
        if (ny != null) {
            strNY = ny;
        }
        RecordSet rs = new RecordSet();
        String strSqlQuery = "SELECT m.ygid,m.ygxm,m.gh,m.year,m.month,m.ny,m.email,detail.应出勤天数,detail.实际出勤天数,迟到次数,早退,旷工,漏签次数,漏签时长,请假时长,出差时长,公出时长\n" +
                " FROM uf_kqycryjlb m,v_kq_report detail WHERE m.yjfszt=0 and m.ygid=detail.userid and m.year=detail.iyear AND m.month=detail.IMONTH ";
        if (!"".equals(strGh)) {
            String[] split_gh = (strGh.replaceAll("，", ",")).split(",");
            strSqlQuery += " and m.gh in('" + StringUtils.join(split_gh, "','") + "')";
        }
        if (!"".equals(strNY)) {
            strSqlQuery += " and m.ny=" + strNY;
        }
        log.info("查询sql:" + strSqlQuery);
        rs.execute(strSqlQuery);

        try {
            String str_userid = "";//人员id
            String str_xm = "";//姓名
            String str_AllDay = "";//应出勤天数
            String str_SjDay = "";//实际出勤天数
            String str_cd = "";//迟到次数
            String str_zt = "";//早退
            String str_kg = "";//旷工
            String str_lq = "";//漏签次数
            String str_lqsc = "";//漏签时长
            String str_qjsc = "";//请假时长
            String str_ccsc = "";//出差时长
            String str_gcsc = "";//公出时长
            String str_year = "";//年
            String str_month = "";//月

            String emailAddress = "";//收件人邮箱
            String emailTitle = "考勤异常提醒";//邮件标题
            String content = "";
            StringBuilder emailContent;
            String response = "";//邮件推送结果

            conn = pool.getConnection();
            statement = conn.createStatement();
            String strInsert="";
            while (rs.next()) {
                emailContent = new StringBuilder();//邮件内容
                str_xm = Utils.null2String(rs.getString("ygxm"));//人员姓名
                str_userid = Utils.null2String(rs.getString("ygid"));//人员姓名
                str_year = Utils.null2String(rs.getString("year"));//年份
                str_month = Utils.null2String(rs.getString("month"));//月份
                str_AllDay = Utils.null2String(rs.getString("应出勤天数"));//应出勤天数
                str_SjDay = Utils.null2String(rs.getString("实际出勤天数"));//实际出勤天数
                str_cd = Utils.null2String(rs.getString("迟到次数"));//迟到次数
                str_zt = Utils.null2String(rs.getString("早退"));//早退
                str_kg = Utils.null2String(rs.getString("旷工"));//旷工
                str_lq = Utils.null2String(rs.getString("漏签次数"));//漏签次数
                str_lqsc = Utils.null2String(rs.getString("漏签时长"));//漏签时长
                str_qjsc = Utils.null2String(rs.getString("请假时长"));//请假时长
                str_ccsc = Utils.null2String(rs.getString("出差时长"));//出差时长
                str_gcsc = Utils.null2String(rs.getString("公出时长"));//公出时长
                emailContent.append("<div>亲爱的【" + str_xm + "】:</div>");
                emailContent.append("<div>   您" + str_year + "年" + str_month + "月考勤存在异常,详细信息为：</div>");
                emailContent.append("<div>   应出勤天数:" + str_AllDay + "天   实际出勤天数:" + str_SjDay + "天</div>");
                emailContent.append("<div>   迟到次数:" + str_cd + "次         早退次数:" + str_zt + "次       旷工次数:" + str_kg + "次</div>");
                emailContent.append("<div>   漏签次数:" + str_lq + "次         漏签天数:" + str_lqsc + "天     请假天数:" + str_qjsc + "天</div>");
                emailContent.append("<div>   出差天数:" + str_ccsc + "天       公出天数:" + str_gcsc + "天</div>");
//            content=emailContent.toString();
                log.info("邮件推送内容：" + emailContent);
                emailContent.append("<p>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------</p>\n");
                emailContent.append("<div style='font-size: large;font-family: 微软雅黑;'>近期发现各部门员工考勤异常问题较多，为减少员工考勤异常问题，故在此温馨提醒以下注意事项：</div>");
                emailContent.append("<div style='font-size: initial;font-family: 微软雅黑;'>  1） 每月1日，企业微信会自动触发流程给考勤有异常的员工，员工可通过考勤异常汇总流程提醒查看上月考勤异常情况，如发现与实际出勤情况不符的考勤异常数据，可提报考勤异常申请流程，但需要在次月4日下班前（如遇节假日，时间不变）完成提报和各个环节审批，并及时确认考勤异常汇总流程提示；</div>");
                emailContent.append("<div style='font-size: initial;font-family: 微软雅黑;'>  2） 如果员工收到考勤异常汇总流程提示没有及时确认，每月5号凌晨系统会自动确认，默认异常情况无问题，考勤报表也将不能进行后续调整；</div>");
                emailContent.append("<div style='font-size: initial;font-family: 微软雅黑;'>  3） 如遇半天外出、请假、巡店等此类考勤情况，打卡时间需按9:00-18:00正常班次进行打卡，没有弹性打卡时间；</div>");
                emailContent.append("<div style='font-size: initial;font-family: 微软雅黑;'>  4） 巡店打卡，以V8系统“签到成功”为准，仅登陆页面，没有“签到成功”的信息显示，不能作为考勤打卡证明；</div>");
                emailContent.append("<div style='font-size: initial;font-family: 微软雅黑;'>  5） 新入职同事请注意，入职当天及之后如没有及时进入企业微信，导致无法打卡的，需要在进入企业微信后发起考勤异常申请流程，所有未打卡日期均需进行补卡，并自行跟进当月流程审批在次月4日前完成。</div>");
                emailContent.append("<div style='font-size: initial;font-family: 微软雅黑;'>  请所有同事及时关注自己的考勤，发现异常及时处理，以免影响您的考勤工资，如对考勤问题有不清楚的地方，可登录云学堂查看考勤制度相关规定，也可以联络北京人力资源共享中心负责考勤工作的同事荘懿宁和孙鹤娜，其他分公司同事可以联络当地分公司HR，公司的规章制度需要大家共同的遵守与维护，感谢您的理解与支持！</div>");


                emailAddress = Utils.null2String(rs.getString("email"));//"17610919982@163.com";
                Boolean result = client.sendExchange(emailAddress, emailTitle, emailContent.toString());
                if (result) {
                    log.info("邮件发送成功！");
                    strInsert = "update uf_kqycryjlb set yjfszt='1',MODEDATAMODIFIER='2',MODEDATAMODIFYDATETIME='" + nowDate + " " + getHourMs() + "' where ygid=" + str_userid + " and year='" + str_year + "' and month='" + str_month + "'";
                    log.info("插入邮件发送成功记录：" + strInsert);
                    statement.addBatch(strInsert);
                    response = "邮件发送成功！";
                } else {
                    response = "邮件发送失败！";
                }
                log.info("邮件推送结果：" + response);
            }
            Long end = new Date().getTime();
            log.info("计划任务耗时：" + (end - begin) / (1000 * 60) + "分钟");
            Long begin1 = System.currentTimeMillis();
            statement.executeBatch();
            Long end1 = System.currentTimeMillis();
            log.info("批量更新耗时：" + (end1 - begin1) / (1000 * 60) + "(分钟)");
            conn.close();
            statement.close();
            log.info("计划任务执行结束======>");
        }catch (Exception ex){
            log.info("计划任务异常：" + ex.toString());
        }
    }
}
